﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using Modbus.Device;
using Modbus.Utility;
using System.Diagnostics;
namespace modBusTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.SizeChanged += new EventHandler(Form1_SizeChanged);

            comboBox1.Items.AddRange(SerialPort.GetPortNames());
        }

        void Form1_SizeChanged(object sender, EventArgs e)
        {
            Control control = (Control)sender;

            // Ensure the Form remains square (Height = Width).
            /*if (control.Size.Height != control.Size.Width)
            {
                control.Size = new Size(control.Size.Width, control.Size.Width);
            }*/

            dataGridView1.Size = new Size(control.Width - 33, control.Height - 393);
            

        }

        private modbusmap registerMap = new modbusmap();
        private handleScript scriptHandler = new handleScript();

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            performDataCommuincation = getData;
            timer1.Start();
        }  
            
            
            //using (SerialPort port = new SerialPort("COM3"))
            //{
            //    // configure serial port
            //    port.BaudRate = 115200;
            //    port.DataBits = 8;
            //    port.Parity = Parity.None;
            //    port.StopBits = StopBits.One;
               
            //    port.Open();

            //    // create modbus master
            //    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            //    byte slaveID = 2;
            //    ushort startAddress = 6;
            //    ushort[] registers = new ushort[] { 1, 2, 3 };

            //    // write three registers
            //    try
            //    {
            //        //master.WriteMultipleRegisters(slaveID, startAddress, registers);
            //        //master.WriteSingleRegister(slaveID, startAddress, 44);
            //        ushort[] input = master.ReadInputRegisters(slaveID, startAddress, 8);
                    
            //        //outputbox.Text = input[0].ToString();
            //        float[] current = new float[4];

            //        current[0] = ModbusUtility.GetSingle(input[0], input[1]);
            //        current[1] = ModbusUtility.GetSingle(input[2], input[3]);
            //        current[2] = ModbusUtility.GetSingle(input[4], input[5]);
            //        current[3] = ModbusUtility.GetSingle(input[6], input[7]);
            //        int i=0;
            //        foreach(float item in current){

            //            dataGridView1.Rows.Insert(i, "Current " + i.ToString(), item.ToString());
            //            i++;
            //        }
                    
                    
            //        //StringBuilder temp=new StringBuilder();

            //        //temp.Append(current[0].ToString()).Append(" ");
            //        //temp.Append(current[1].ToString()).Append(" ");
            //        //temp.Append(current[2].ToString()).Append(" ").Append(current[3].ToString()).Append(" ");
            //        //outputbox.Text = temp.ToString();


            //        //DataGridViewRow newRow = new DataGridViewRow();


            //        //dataGridView1.Rows.Add();
            //        //dataGridView1.Rows.Insert(0, "hello", 3);
                
                
            //    }
            //    catch (Exception err)
            //    {
            //        outputbox.Text = err.Message;
                
            //    }
            //}


        private void log(string line)
        {
            outputbox.Text = outputbox.Text + line + Environment.NewLine;
        }
        

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void ReadMap_Click(object sender, EventArgs e)
        {
            try
            {
                registerMap.readData(FileName.Text);
            }
            catch (Exception err)
            {
                log(err.Message);
                return;
            }

 
            
        }

        private void openFile_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            FileName.Text = openFileDialog1.FileName;
        }

        private void clear_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
        }

        private void ReadScript_Click(object sender, EventArgs e)
        {
            try
            {
                scriptHandler.readData(FileName.Text);
            }
            catch (Exception err)
            {
                log(err.Message);
                //throw;
            }

            log("Done Reading Script");
            //scriptHandler.writeData();
           
        }

        private void RunScript_Click(object sender, EventArgs e)
        {
            //scriptHandler
            //scriptHandler.comPort = comboBox1.SelectedText;
            //scriptHandler.modbusId = Int32.Parse(textBox1.Text);
            
            try
            {
                command.comPort = comboBox1.SelectedItem.ToString();
                command.modbusId = Int32.Parse(textBox1.Text);

                scriptHandler.writeData();

                string[] temp = scriptHandler.getResults();

                foreach (string item in temp)
                {
                    log(item);
                }
            }
            catch (Exception err)
            {
                log(err.Message);
                log("Check to ensure com port is correctly selected and modbus ID is correct");
                //throw;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            performDataCommuincation();
            if (!checkBox1.Checked)
            {
                timer1.Stop();
            }

        }



        private void trySomething()
        {
            SerialPort port = new SerialPort(comboBox1.SelectedItem.ToString());
            
                // configure serial port
                port.BaudRate = 115200;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;

                try
                {
                    if(!port.IsOpen)
                        port.Open();
                }
                catch (Exception err)
                {
                    log(err.Message);
                    return;
                }

                // create modbus master
                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                byte slaveID = byte.Parse(textBox1.Text);
                master.Transport.ReadTimeout = 100;

                dataGridView1.Rows.Clear();
                registerMap.master = master;
                registerMap.slaveID = 49;
                
                long time = registerMap.getData();

                log(time.ToString());
                
                List<mapFields> mapItems = registerMap.getList();

                foreach (mapFields item in mapItems)
                {
                    dataGridView1.Rows.Insert(0,item.paramName, item.value);
                }

                dataGridView1.Update();
                port.Close();
                //registerMap.
        }
        private delegate void performDataCommuincationDelegate();
        performDataCommuincationDelegate performDataCommuincation;
        private void getData()
        {
            using (SerialPort port = new SerialPort(comboBox1.SelectedItem.ToString()))
            {
                // configure serial port
                port.BaudRate = 115200;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;

                try
                {
                    if (!port.IsOpen)
                    {
                        port.Open();
                    }
                }
                catch (Exception err)
                {
                    log(err.Message);
                    return;
                }

                // create modbus master
                IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                byte slaveID = byte.Parse(textBox1.Text);
                master.Transport.ReadTimeout = 100;
  
                dataGridView1.Rows.Clear();
 
                // time how long this operation takes 
                Stopwatch timer = new Stopwatch();
                timer.Reset();
                timer.Start();
                List<mapFields> mapItems = registerMap.getList();
                for (int i = 0; i < mapItems.Count; i++)
                {

                    try
                    {
                        //handle holding registers
                        if (mapItems[i].registerType == mapFields.regType.holding)
                        {
                            if (mapItems[i].type == mapFields.paramType.word_t)
                            {
                                // handle normal registers
                                ushort[] input = master.ReadHoldingRegisters(slaveID, (ushort)(mapItems[i].register - 40000 - 1), 1);
                                //dataGridView1.Rows.Insert(0, mapItems[i].paramName, input[0]);
                            }
                            else
                            {
                                //handle floats
                                ushort[] input = master.ReadHoldingRegisters(slaveID, (ushort)(mapItems[i].register - 40000 - 1), 2);
                                //dataGridView1.Rows.Insert(0, mapItems[i].paramName, ModbusUtility.GetSingle(input[0], input[1]));
                            }
                        }
                        else if (mapItems[i].registerType == mapFields.regType.input)
                        {
                            if (mapItems[i].type == mapFields.paramType.word_t)
                            {
                                ushort[] input = master.ReadInputRegisters(slaveID, (ushort)(mapItems[i].register - 30000 - 1), 1);
                                //dataGridView1.Rows.Insert(0, mapItems[i].paramName, input[0]);
                            }
                            else
                            {
                                ushort[] input = master.ReadInputRegisters(slaveID, (ushort)(mapItems[i].register - 30000 - 1), 2);
                                //dataGridView1.Rows.Insert(0, mapItems[i].paramName, ModbusUtility.GetSingle(input[0], input[1]));
                            }
                        }

                    }
                    catch (Exception err)
                    {
                        log(err.Message);

                    }
                }
                timer.Stop();
                log(timer.ElapsedMilliseconds.ToString());
                //outputbox.Text = outputbox.Text + timer.ElapsedMilliseconds.ToString() + Environment.NewLine;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            performDataCommuincation = trySomething;
            timer1.Interval = 1000;
            timer1.Start();
            
            
            
            
            return;
            
            optimizeRange test = new optimizeRange();
            test.addRegister(1);
            test.addRegister(2);
            test.addRegister(3);
            test.addRegister(4);
            test.addRegister(7);
            test.addRegister(11);
            test.addRegister(12);
            test.addRegister(13);
            test.solve();
            List <pair> solution = test.getSolution();


            
            
            
            
            
            
            SerialPort port = new SerialPort(comboBox1.SelectedItem.ToString());
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

            byte slaveID = byte.Parse(textBox1.Text);
            master.Transport.ReadTimeout = 100;

            port.BaudRate = 115200;
            port.DataBits = 8;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;

            try
            {
                port.Open();
            }
            catch (Exception err)
            {
                log(err.Message);
                return;
            }
            

            // time how long this operation takes 
            Stopwatch timer = new Stopwatch();
            timer.Reset();
            timer.Start();
            ushort[] input = master.ReadHoldingRegisters(slaveID, (ushort) 8300, 125);
            timer.Stop();
            log(timer.ElapsedMilliseconds.ToString());

            foreach (ushort item in input)
            {
                log(item.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            test = new UserControl1();
            
            test.Show();
            
        }

        UserControl1 test;

    }
}
